package com.xucy.springboot.designmodel.creational.single;

/**
 * @Author xucy
 * @Date 2019-07-17 11:27
 * @Description
 **/

public class ThreadLocalInstance {

    private static final ThreadLocal<ThreadLocalInstance> threadLocal=
            new ThreadLocal<ThreadLocalInstance>(){
                @Override
                protected ThreadLocalInstance initialValue() {
                    return new ThreadLocalInstance();
                }
            };

    private ThreadLocalInstance(){

    }

    public static ThreadLocalInstance getInstance(){
        return threadLocal.get();
    }

    public static void main(String[] args) {

        //com.xucy.springboot.designmodel.creational.single.ThreadLocalInstance@3d646c37
        ThreadLocalInstance threadLocalInstance=ThreadLocalInstance.getInstance();
        //com.xucy.springboot.designmodel.creational.single.ThreadLocalInstance@3d646c37
        ThreadLocalInstance threadLocalInstance1=ThreadLocalInstance.getInstance();


        new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadLocalInstance threadLocalInstance=ThreadLocalInstance.getInstance();
                //不一致
                System.out.println(threadLocalInstance);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadLocalInstance threadLocalInstance=ThreadLocalInstance.getInstance();
                //不一致
                System.out.println(threadLocalInstance);
            }
        }).start();

        //threadLocal式单例模式，每个线程的自己的变量总是相同的。
        System.out.println(threadLocalInstance);
        System.out.println(threadLocalInstance1);
    }
}
